package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.helper.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: TODO
 * @author: 化一帆
 * @date: 2022/12/4 18:29
 * @version: v1.0
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    PatientService patientService;


    /**
     * @description: 登录接口   1.从redis获取验证码，判断前端传过来的验证码是否正确   2.判断手机号是否已经注册
     * @author 化一帆
     * @date 2022/12/4 18:36
     */
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        String openid = loginVo.getOpenid();
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        //校验验证码是否正确【验证码第一步】
        //根据手机号去redis中查询正确的验证码。和code比较
        String code_redis = stringRedisTemplate.boundValueOps(phone).get();
        if (!code.equals(code_redis)) {
            throw new YyghException(20001, "验证码不正确");
        }


        if (StringUtils.isEmpty(openid)) {
            //手机号直接登录
            if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
                throw new YyghException(20001, "参数为空");
            }

            //从数据库中查询手机号存不存在
            UserInfo userInfo = this.getUserInfoByPhone(phone);

            if (userInfo == null) {
                //手机号码不存在，完成自动注册
                UserInfo userInfo1 = new UserInfo();
                userInfo1.setPhone(phone);
                userInfo1.setAuthStatus(0);//未认证
                userInfo1.setStatus(1);
                userInfo1.setCreateTime(new Date());
                userInfo1.setUpdateTime(new Date());
                baseMapper.insert(userInfo1);
            }

            if (userInfo.getStatus() == 0) {
                throw new YyghException(20001, "用户已经被锁定");
            }

            //验证码校验通过并且用户的状态为非锁定，就能说明已经登录成功
            HashMap<String, Object> map = new HashMap<>();
            String name = userInfo.getName(); //用户真实姓名
            if (StringUtils.isEmpty(name)) {
                String nickName = userInfo.getNickName();//微信昵称
                name = nickName;
                if (StringUtils.isEmpty(name)) {
                    String phone1 = userInfo.getPhone(); //手机号
                    name = phone1;
                }
            }
            map.put("name", name);

            //服务端使用jjwt组件创建了jwt令牌，客户端（浏览器）自行存储该令牌到（cookie）
            //每次向后端服务器发送请求都会携带token，需要后端进行解析判断
            String token = JwtHelper.createToken(userInfo.getId(), userInfo.getName());
            map.put("token", token);
            return map;
        } else {
            //绑定手机号
            //7、根据openid查询用户
            UserInfo userInfo = this.getUserInfoByOpenId(openid);

            //8、页面上绑定手机号，根据输入的手机号，查询是否存在

            UserInfo userInfoByPhone = this.getUserInfoByPhone(phone);

            //9、不存在，直接绑定即可
            if (userInfoByPhone == null) {
                userInfo.setPhone(phone);
                this.updateById(userInfo);
            } else {
                //10、手机号已经存在（以前直接通过该手机号去登录过）
                //两天数据合并，最后删除其中一条
                userInfo.setName(userInfoByPhone.getName());
                userInfo.setCertificatesType(userInfoByPhone.getCertificatesType());
                userInfo.setCertificatesNo(userInfoByPhone.getCertificatesNo());
                userInfo.setCertificatesUrl(userInfoByPhone.getCertificatesUrl());
                userInfo.setPhone(phone);
                userInfo.setAuthStatus(userInfoByPhone.getAuthStatus());

                this.updateById(userInfo);
                this.removeById(userInfoByPhone.getId());
            }
            return this.get(userInfo);
        }

    }

    private Map get(UserInfo userInfo) {
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();//真实姓名
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();//微信昵称
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
        }
        map.put("name", name);// name  nickname  phone

        //服务端使用jjwt组件创建了jwt令牌，客户端（浏览器）自行存储该令牌（cookie）
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);

        return map;
    }


    @Override
    public UserInfo getUserInfoByOpenId(String openid) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid", openid);//手机号不能重复
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        return userInfo;
    }


    private UserInfo getUserInfoByPhone(String phone) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);//手机号不能重复
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        return userInfo;
    }

    /**
     * @description: 用户认证，查询当前的用户，封装用户信息
     * @author 化一帆
     * @date 2022/12/6 15:42
     */
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //1.根据userid查询当前操作的用户的信息
        UserInfo userInfo = baseMapper.selectById(userId);

        //2.封装参数的vo对象取值给userinfo赋值
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());

        //设置认证状态-认证中
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());

        //进行信息更新
        baseMapper.updateById(userInfo);
    }


    /**
     * @description: 查询用户信息 ，带条件分页
     * @author 化一帆
     * @date 2022/12/6 20:22
     */
    @Override
    public Page<UserInfo> userList(Integer page, Integer limit, UserInfoQueryVo userInfoQueryVo) {
        Page<UserInfo> userInfoPage = new Page<>(page, limit);

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();


        String keyword = userInfoQueryVo.getKeyword();//用户名
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();


        if (!StringUtils.isEmpty(keyword)) {
            queryWrapper.like("name", keyword);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            queryWrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            queryWrapper.le("create_time", createTimeEnd);
        }


        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();

        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("status", status);
        }

        if (!StringUtils.isEmpty(authStatus)) {
            queryWrapper.eq("auth_status", authStatus);
        }

        baseMapper.selectPage(userInfoPage, queryWrapper);


        //从page分页对象中获取所有的用户进行遍历，将状态赋值为字符串显示
        userInfoPage.getRecords().forEach(userInfo -> {
            Integer status1 = userInfo.getStatus();
            Integer authStatus1 = userInfo.getAuthStatus();

            String authStatusString = AuthStatusEnum.getStatusNameByStatus(authStatus1);
            String statusString = status1 == 1 ? "正常" : "锁定";

            userInfo.getParam().put("authStatusString", authStatusString);
            userInfo.getParam().put("statusString", statusString);

        });

        return userInfoPage;
    }


    /**
     * @description: 设置用户状态
     * @author 化一帆
     * @date 2022/12/6 21:14
     */

    @Override
    public void lock(Long id, Integer status) {
        UserInfo userInfo = baseMapper.selectById(id);
        userInfo.setStatus(status);
        baseMapper.updateById(userInfo);
    }

    /**
     * @description:  查看按钮的功能实现
     * 根据id查询用户的信息+用户所属的就诊人
     * @author 化一帆
     * @date 2022/12/6 21:23
     */
    @Override
    public Map<String, Object> show(Long id) {
        UserInfo userInfo = baseMapper.selectById(id);
        this.packUserInfo(userInfo);
        List<Patient> list = patientService.findListByUserId(id);

        Map<String,Object> map = new HashMap<>();
        map.put("userInfo",userInfo);
        map.put("patientList",list);

        return map;
    }

    private void packUserInfo(UserInfo userInfo) {
        Integer status = userInfo.getStatus();
        userInfo.getParam().put("statusString",status==1?"正常":"锁定");
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
    }

    /**
     * @description: 用户认证
     * @author 化一帆
     * @date 2022/12/8 15:10
     */
//认证审批  2通过  -1不通过
    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

}

